package com.github.llyb120.mugen;

import cn.hutool.core.io.IoUtil;
import lombok.Cleanup;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipFileLoader implements PluginFileLoader{

    @Overrule
    public boolean match(String extName) {
        return extName.equals("zip");
    }

    @Overrule
    public Map<String, ByteClass> analyze(PluginOption option, List<File> files) {
        Map<String, ByteClass> ret = new HashMap<>();
        try{
            for (File file : files) {
                @Cleanup FileInputStream fis = new FileInputStream(file);
                ZipInputStream zin = new ZipInputStream(fis);
                ZipEntry entry = null;
                while((entry=zin.getNextEntry())!=null){
                    if(entry.isDirectory()||entry.getName().equals("..\\"))
                        continue;
                    if(!entry.getName().endsWith(".class")){
                        continue;
                    }
                    String className = option.getBasePackage() + "." + (entry.getName())
                            .replace(".class", "")
                            .replaceAll("\\\\|/", ".");;
                    byte[] bytes = IoUtil.readBytes(zin, false);
                    ByteClass byteclass = ByteClass.builder()
                            .className(className)
                            .bytes(bytes)
                            .build();
                    ret.put(byteclass.getClassName(), byteclass);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

}
